import random
# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.verifications.constant import SMS_CODE_EXPIRATION_TIME, YUNTONGXUN_EXPIRATION_TIME,\
    YUNTONGXUN_TEMPLATE
from libs.captcha.captcha import captcha
from django import http
import logging

from libs.yuntongxun.sms import CCP
from utils.response_code import RETCODE

logger = logging.getLogger('django')
#图形验证码
class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpeg
        """
        # 生成图片验证码
        text, image = captcha.generate_captcha()

        # 保存图片验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % uuid, 120, text)

        # 响应图片验证码
        return http.HttpResponse(image, content_type='image/jpeg')

#短信验证码
class SMSCodeView(View):
    """短信验证码"""

    def get(self, reqeust, mobile):
        """
        :param reqeust: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        # 接收参数
        image_code_client = reqeust.GET.get('image_code')
        uuid = reqeust.GET.get('image_code_id')

        #校验参数是否齐全
        if not all(image_code_client):
            return http.HttpResponseBadRequest('缺少必填信息')


        # 创建连接到redis的对象
        redis_conn = get_redis_connection('code')

        # 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)

        if image_code_server is None:
            # 图形验证码过期或者不存在
            return http.HttpResponseBadRequest('图形验证码失效')
        # 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)

        # 对比图形验证码
        image_code_server = image_code_server.decode()  # bytes转字符串
        if image_code_client.lower() != image_code_server.lower():  # 转小写后比较
            return http.HttpResponseBadRequest('验证码不一致')

            #先获取有没有标记位
        send_flag=redis_conn.get('send_flag_%s'%mobile)
        if send_flag is not None:
            return http.HttpResponseBadRequest('操作太频繁')

        # 生成短信验证码：生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        #导入包
        from redis import StrictRedis

        # 通过redis实例创建管道
        pl = redis_conn.pipeline()
        # 将下面两个指令缓存到管道中

        # 保存短信验证码
        redis_conn.setex('sms_%s' % mobile, SMS_CODE_EXPIRATION_TIME, sms_code)

        # 避免频繁发送短信验证码
        # 设置标记位
        redis_conn.setex('send_flag_%s' % mobile,60,1)

        #执行管道
        pl.execute()


        # 发送短信验证码
        #CCP().send_template_sms(mobile,[sms_code, YUNTONGXUN_EXPIRATION_TIME], YUNTONGXUN_TEMPLATE)

        #将发送短信改为celery
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)


        # 响应结果
        return http.JsonResponse({'code':RETCODE.OK})





